package cz.swosh.stomp.web;



import org.apache.openejb.assembler.classic.EnterpriseBeanInfo;
import org.apache.openejb.assembler.classic.Assembler;
import org.apache.openejb.assembler.classic.AppInfo;
import org.apache.openejb.assembler.classic.EjbJarInfo;
import org.apache.openejb.loader.SystemInstance;

import java.util.Collection;
import java.util.List;

/**
 *
 * @author převzato z http://openejb.apache.org/functional-testing-with-openejb-jetty-and-selenium.html
 */
public class EJBHelper {
    public EnterpriseBeanInfo getEJBInfo(String ejbLink) {
        Collection<AppInfo> deployedApplications = getDeployedApps();
        for (AppInfo app : deployedApplications) {
            List<EjbJarInfo> ejbJars = app.ejbJars;
            for (EjbJarInfo ejbJar : ejbJars) {
                List<EnterpriseBeanInfo> enterpriseBeans = ejbJar.enterpriseBeans;
                for (EnterpriseBeanInfo enterpriseBean : enterpriseBeans) {
                    if (enterpriseBean.ejbDeploymentId.equals(ejbLink)) {
                        return enterpriseBean;
                    }
                }
            }
        }

        return null;
    }

    public EnterpriseBeanInfo getBeanInfo(Class<?> fieldType) {
        Collection<AppInfo> deployedApplications = getDeployedApps();

        for (AppInfo deployedApplication : deployedApplications) {
            List<EjbJarInfo> ejbJars = deployedApplication.ejbJars;

            for (EjbJarInfo ejbJar : ejbJars) {
                List<EnterpriseBeanInfo> enterpriseBeans = ejbJar.enterpriseBeans;

                for (EnterpriseBeanInfo enterpriseBean : enterpriseBeans) {
                    List<String> remoteInterfaces = enterpriseBean.businessRemote;
                    String ftcn = fieldType.getCanonicalName() + "Remote";
                    if (remoteInterfaces.contains(ftcn)) {
                        return enterpriseBean;
                    }
                }
            }
        }

        return null;
    }

    private Collection<AppInfo> getDeployedApps() {
        Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
        return assembler.getDeployedApplications();
    }
}
